package com.smashcrush.client.desktop;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JFrame;

import org.jboss.resteasy.client.ProxyFactory;
import org.jboss.resteasy.plugins.providers.RegisterBuiltin;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

import com.smashcrush.client.rest.ClientTestingService;
import com.smashcrush.model.BrowserType;
import com.smashcrush.model.Script;

public class Desktop extends JFrame {

	ClientTestingService client;

	String token = "abc";

	public static void main(String[] args) {
		Desktop desktop = new Desktop();
		try {
			desktop.setupSystray();
			desktop.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Desktop() {
		RegisterBuiltin.register(ResteasyProviderFactory.getInstance());

		client = ProxyFactory.create(ClientTestingService.class,
				"http://localhost:8080");

		// JTextField jlbHelloWorld = new JTextField("abc");
		// add(jlbHelloWorld);
		// setSize(100, 100);

	}

	public void start() {
		Thread thread = new Thread() {
			public void run() {
				while (true) {
					poll();
				}
			}
		};
		thread.start();
	}

	private void poll() {
		System.out.println("polling!");

		try {

			Script script = client.pollScript(token);

			if (script != null) {
				executeScript(script);
			}

			Thread.sleep(1000);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void setupSystray() {
		if (SystemTray.isSupported()) {

			SystemTray tray = SystemTray.getSystemTray();
			URL logoUrl = Desktop.class.getResource("logo.png");
			Image image = Toolkit.getDefaultToolkit().getImage(logoUrl);

			MouseListener mouseListener = new MouseListener() {

				public void mouseClicked(MouseEvent e) {
					System.out.println("Tray Icon - Mouse clicked!");
				}

				public void mouseEntered(MouseEvent e) {
					System.out.println("Tray Icon - Mouse entered!");
				}

				public void mouseExited(MouseEvent e) {
					System.out.println("Tray Icon - Mouse exited!");
				}

				public void mousePressed(MouseEvent e) {
					System.out.println("Tray Icon - Mouse pressed!");
				}

				public void mouseReleased(MouseEvent e) {
					System.out.println("Tray Icon - Mouse released!");
				}
			};

			ActionListener exitListener = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("Exiting...");
					System.exit(0);
				}
			};

			PopupMenu popup = new PopupMenu();
			MenuItem defaultItem = new MenuItem("Exit");
			defaultItem.addActionListener(exitListener);
			popup.add(defaultItem);

			final TrayIcon trayIcon = new TrayIcon(image, "Tray Demo", popup);

			ActionListener actionListener = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					trayIcon.displayMessage("Action Event",
							"An Action Event Has Been Performed!",
							TrayIcon.MessageType.INFO);
				}
			};

			trayIcon.setImageAutoSize(true);
			trayIcon.addActionListener(actionListener);
			trayIcon.addMouseListener(mouseListener);

			try {
				tray.add(trayIcon);
			} catch (AWTException e) {
				System.err.println("TrayIcon could not be added.");
			}

		} else {

			// System Tray is not supported

		}
	}

	private void executeScript(Script script) {
		System.out.println("EXECUTING!!!\n" + script);

		Map<String, String> results = new HashMap<String, String>();

		ScriptEngineManager factory = new ScriptEngineManager();
		ScriptEngine engine = factory.getEngineByName("groovy");

		WebDriver browser = null;

		if (script.getBrowserType().equals(BrowserType.Chrome)) {
			browser = new ChromeDriver();
		} else if (script.getBrowserType().equals(BrowserType.FireFox)) {
			browser = new FirefoxDriver();
		} else if (script.getBrowserType().equals(BrowserType.HtmlUnit)) {
			browser = new HtmlUnitDriver();
		} else if (script.getBrowserType().equals(BrowserType.IE)) {
			browser = new InternetExplorerDriver();
		}

		engine.put("browser", browser);
		engine.put("results", results);

		try {
			engine.eval("import org.openqa.selenium.By\n" + script.getSource());
		} catch (ScriptException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		client.pushResults(token, results);
		browser.close();
	}

}
